﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Collections;
using System.Threading;
using System.Text.RegularExpressions;
using ImageScale.Properties;

namespace ImageScale
{
    public partial class FtpTransferForm : Form
    {
        private ScaleClass _scaleClass;
        private mainFormData _formData;

        public FtpTransferForm(mainFormData formData, ScaleClass sc)
        {
            InitializeComponent();
            _formData = formData;
            _scaleClass = sc;
            transferWorker.RunWorkerAsync();
        }

        private void UploadFile(MemoryStream imageStream, string fileName, DoWorkEventArgs e)
        {
            try
            {
                transferWorker.ReportProgress(0, String.Format(@"{0} {1}", Resources.PROMPT_SENDING, fileName));
                int fileSize = (int)imageStream.Length;
                Uri ftpUri = new Uri(String.Format(@"{0}/{1}", _formData.FtpSite, fileName));
                if (ftpUri.Scheme == Uri.UriSchemeFtp)
                {
                    FtpWebRequest ftpRequest = FtpWebRequest.Create(ftpUri) as FtpWebRequest;
                    ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                    ftpRequest.KeepAlive = false;
                    ftpRequest.Credentials = new NetworkCredential(_formData.FtpUser, _formData.FtpPass);
                    Stream ftpStream = ftpRequest.GetRequestStream();
                    imageStream.Seek(0, SeekOrigin.Begin);
                    const int bufferLength = 8 * 1024; // 8 KB
                    byte[] buffer = new byte[bufferLength];
                    int count = 0;
                    int readBytes = 0;
                    do
                    {
                        readBytes = imageStream.Read(buffer, 0, bufferLength);
                        ftpStream.Write(buffer, 0, readBytes);
                        count += readBytes;
                        float uploaded = (float)count / fileSize;
                        int percent = (int)(uploaded * 100);
                        transferWorker.ReportProgress(percent);
                    }
                    while (readBytes != 0);
                    ftpStream.Close();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                transferWorker.CancelAsync();
            }
        }

        private void transferWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (ImageInfo image in _formData.Images)
            {
                Bitmap outBitmap = _scaleClass.Scale(image.Picture);
                MemoryStream imageStream = new MemoryStream();
                outBitmap.Save(imageStream, image.Picture.RawFormat);
                UploadFile(imageStream, Path.GetFileName(image.ImagePath), e);
            }
        }

        private void transferWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState != null)
            {
                fileLabel.Text = e.UserState.ToString();
            }
            transferProgress.Value = e.ProgressPercentage;
        }

        private void transferWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            transferProgress.Value = 0;
            DialogResult = DialogResult.OK;
        }

        private void FtpTransferForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (transferWorker.IsBusy)
            {
                if (MessageBox.Show(Resources.PROMPT_ABORT_FTP, Resources.WARNING, MessageBoxButtons.YesNo, 
                    MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    transferWorker.CancelAsync();
                    DialogResult = DialogResult.None;
                }
            }
        }
    }

}
